﻿@using OSBIDE.Library
@using OSBIDE.Library.Models
@using OSBIDE.Web.Models.ViewModels
@using OSBIDE.Library.Events
@using OSBIDE.Web.Models
@using System.Collections.Generic
@model FeedViewModel
<section>
    @Html.ActionLink("Load earlier posts...", "Index", new { timestamp = Model.LastPollDate.AddHours(-10).Ticks, errorType = Model.SelectedErrorType.Id }, new { id = "load-old-posts" })
</section>
<div id="hidden-workspace">
</div>
<div id="hidden-updates-workspace" style="display: none;"></div>
<script type="text/javascript">

    var AllComments = {};

    $(document).ready(function () {

        //get recent feed items
        getRecentFeedItems();

        //display hidden
        showLastHidden();

        //get comment updates
        getCommentUpdates();

        //listen for clicks to load older messages
        $("#load-old-posts").click(function (e) {
            e.preventDefault();
            $("#load-old-posts").text("Loading...");
            var feedId = getOldestFeedId();
            $.ajax(
            {
                url: "@Url.Action("OldFeedItems", "Feed")",
                data: { id: feedId, count: 30, userId: "@Model.SingleUserId", errorType: "@Model.SelectedErrorType.Id" },
                dataType: "html",
                type: "GET",
                success: getOldPostsSuccess,
            }
            );
        });

        //disable footer selection
        $('.feed-item-footer').disableSelection();
    }
    );

    //called when the user clicks on the "Load Earlier Posts..." link at the bottom of the page
    function getOldPostsSuccess(html) {
        $("#load-old-posts").text("Load earlier posts...");
        var trimmed = $.trim(html);
        if (trimmed.length > 0) {
            $("#feed-items").append(html);
            parseDates();
            $(".feed-item-ajax:hidden.OldFeedItems").each(function (e) {
                $(this).removeClass("feed-item-ajax");
            });
        }
        else {
            $("#load-old-posts").text("No earlier posts available.");
        }
    }

    //Updates KnockoutJS models for feed item conversations
    function expandComments(element) {

        //change text as appropriate
        var commentsTextSpan = "#expand-comments-text-" + element;
        if ($(commentsTextSpan).text() == "View") {
            $(commentsTextSpan).text("Hide");
        }
        else {
            $(commentsTextSpan).text("View");
        }

        //if the user clicked hide, hide the comments now
        //display comments
        var commentsDiv = "#feed-item-comments-" + element;
        if ($(commentsDiv).find('.log-comment-single').length > 0) {
            if ($(commentsDiv).css('display') != 'none') {
                $(commentsDiv).css('display', 'none');
            }
            else {

                //ask server for comments
                $.ajax(
                    {
                        url: "@Url.Action("GetComments", "Feed")",
                        data: { singleLogId: element },
                        dataType: "json",
                        type: "GET",
                        success: expandCommentsSuccess
                    }
            );
            }
        }
    }

    //Called after successful AJAX call to get feed item comments
    function expandCommentsSuccess(result) {

        //update view model
        updateFeedItemViewModel(result);

        //display comments
        var commentsDiv = "#feed-item-comments-" + result.Data[0].OriginalLogId;
        $(commentsDiv).css('display', 'block');
    }

    //Updates a KO view model using the supplied JS object
    function updateFeedItemViewModel(jsObject) {

        $.each(jsObject.Data, function (index, value) {

            //bind to new view model
            var model = {
                Comments: value.Comments,
                NumberOfComments: ko.observable(value.Comments.length),
                LastUpdated: ko.observable(new Date())
            };

            //model mapping
            var mapping =
                {
                    'Comments': {
                        key: function (item) {
                            return ko.utils.unwrapObservable(item.CommentId);
                        }
                    }
                };

            //compute local time
            $(model.Comments).each(function (index) {

                var milliseconds = model.Comments[index].UtcUnixDate + "";
                var formatString = "MM/DD/YYYY hh:mm A";
                var currentDate = moment.utc(milliseconds, 'X');
                var localDate = new Date();
                var localOffset = localDate.getTimezoneOffset();
                currentDate = currentDate.subtract('minutes', localOffset);
                model.Comments[index]['LocalDate'] = currentDate.format(formatString);
            });

            var toBind = "feed-item-" + value.OriginalLogId;

            //view model doesn't exist, create one
            if (!AllComments[value.ActualLogId]) {

                AllComments[value.ActualLogId] = ko.mapping.fromJS(model, mapping);
            }

            //update view model with server data
            ko.mapping.fromJS(model, AllComments[value.ActualLogId]);

            //apply binding if one doesn't already exist
            if (!ko.dataFor(document.getElementById(toBind))) {
                ko.applyBindings(AllComments[value.ActualLogId], document.getElementById(toBind));
            }
        });
    }

    //Periodically updates view models for feed items.  Useful for displaying an updated count
    //of comments for a given feed item.
    function getCommentUpdates() {

        var ModelIds = Array();

        //request comment updates for all feed items
        $(".feed-item-single").each(function (index) {
            var log_id = $(this).attr("data-id");
            ModelIds.push(log_id);
        });

        //make the ajax call
        $.ajax(
            {
                url: "@Url.Action("GetComments", "Feed")",
                data: { logIds: JSON.stringify(ModelIds) },
                dataType: "json",
                type: "POST",
                success: updateFeedItemViewModel
            });

        //call ourselves again in 20 seconds
        setTimeout(getCommentUpdates, 20000)
    }

    //called when the user clicks the "Send" button
    function sendResponse(elementId) {
        var textAreaId = '#feed-item-respond-' + elementId;
        var textArea = $(textAreaId);

        //get and clear user response
        var userResponse = textArea.val();
        textArea.val("");

        //submit response using AJAX
        $.ajax(
                        {
                            url: "@Url.Action("PostCommentAsync", "Feed")",
                            data: { logId: elementId, comment: userResponse },
                            dataType: "json",
                            type: "POST",
                            success: function (data) {
                                if (!$.isEmptyObject(data)) {
                                    var commentsTextSpan = "#expand-comments-text-" + data.OriginalLogId;
                                    $(commentsTextSpan).text("Hide");
                                    expandCommentsSuccess(data);
                                }
                            }
                        });
    }

    function showLastHidden() {
        var initialScrollHeight = $(document).scrollTop();
        var item = $(".feed-item-ajax:hidden").last();

        //if we're loading old items,
        if (item.hasClass("OldFeedItems")) {
            item = $(".feed-item-ajax:hidden.OldFeedItems").first();
        }
        item.slideDown(
                {
                    duration: 600,
                    easing: "linear",
                    progress: function (animation, progress, remainingMs) {
                        if (initialScrollHeight > 50) {
                            $(document).scrollTop($(this).height() + initialScrollHeight);
                        }
                    }
                });
        parseDates();
        setTimeout(showLastHidden, 4000);
    }

    function getOldestFeedId() {
        var lastId = $(".feed-item-single").last().attr("data-id");
        if (lastId == undefined) {
            lastId = "@(Model.LastLogId + 1)";
        }
        return lastId;
    }

    function getMostRecentFeedId() {
        var lastId = $(".feed-item-single").first().attr("data-id");
        if (lastId == undefined) {
            lastId = "@Model.LastLogId";
        }
        return lastId;
    }

    function getRecentFeedItems() {

        //find most recent log id
        var lastId = getMostRecentFeedId();
        $.ajax(
            {
                url: "@Url.Action("RecentFeedItems", "Feed")",
                data: { id: lastId, userId: "@Model.SingleUserId", errorType: "@Model.SelectedErrorType.Id" },
                dataType: "html",
                type: "GET",
                success: getRecentFeedItemsSuccess,
                complete: function () { setTimeout(getRecentFeedItems, 30000); }
            }
            );
    }

    function getRecentFeedItemsSuccess(html) {
        var trimmed = $.trim(html);
        if (trimmed.length > 0) {
            $("#hidden-workspace").append(html);
            parseDates();
            if ($("#hidden-workspace").find('.feed-item-single').length > 0) {
                $("#feed-items").prepend(html);
            }
            $("#hidden-workspace").empty();
        }
    }


</script>
